<template>
  <div class="venue-list">
    <!-- 搜索表单 -->
    <el-form   
      :inline="true"
      :model="query"
      class="demo-form-inline"
      size="small"
    >
      <el-form-item label="场馆名称">
        <el-input v-model="query.name" placeholder="请输入场馆名称" clearable>
          <template #prefix>
            <el-icon class="el-input__icon"><search /></el-icon
          ></template>
        </el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="query.status" placeholder="请选择状态" clearable>
          <el-option label="开放" value="open" />
          <el-option label="关闭" value="closed" />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" v-if="user && [1,2].includes(user.role)">
        <el-select v-model="query.type" placeholder="请选择类型" clearable>
          <el-option

            v-for="(label, value) in roleType"
            :key="value"
            :label="label"
            :value="value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="load">查询</el-button>
        <el-button type="danger" @click="clear">重置</el-button>
        <el-button v-if="isAdmin" type="success" @click="openAddDialog"
          >添加场馆</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 场馆数据表格 -->
    <el-table
      :data="venues"
      border
      stripe
      v-loading="loading"
      :max-height="getTableHeight()"
    >
      <el-table-column prop="venueId" label="场馆ID" sortable />
      <el-table-column prop="name" label="场馆名称" />
      <el-table-column prop="address" label="地址" />
      <el-table-column prop="capacity" label="容纳人数" sortable />
      <el-table-column prop="availableTimes" label="开放时间" width="300">
        <template #default="scope">
          {{ formatTimes(scope.row.availableTimes) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'open' ? 'success' : 'danger'">
            {{ scope.row.status === 'open' ? '开放' : '关闭' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="role" label="类型">
        <template #default="{ row }">{{ roleType[row.role] }}</template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="220">
        <template #default="scope">
          <el-button
            v-if="isAdmin"
            size="small"
            @click="openEditDialog(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="handleReservation(scope.row)"
            :disabled="scope.row.status !== 'open'"
            >预约</el-button
          >
          <el-popconfirm
            v-if="isAdmin"
            title="确认删除?"
            @confirm="handleDelete(scope.row.venueId)"
          >
            <template #reference>
              <el-button v-if="isAdmin" type="danger" size="small"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="current"
      v-model:page-size="size"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 添加/编辑场馆对话框 -->
    <el-dialog
      v-model="addEditDialogVisible"
      :title="editMode ? '编辑场馆' : '添加场馆'"
    >
      <el-form
        :model="addEditForm"
        :rules="rules"
        ref="addEditFormRef"
        label-width="100px"
      >
        <el-form-item label="场馆名称" prop="name">
          <el-input
            v-model="addEditForm.name"
            placeholder="请输入场馆名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input
            v-model="addEditForm.address"
            placeholder="请输入场馆地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="容纳人数" prop="capacity">
          <el-input-number
            v-model="addEditForm.capacity"
            :min="1"
            :max="100000"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="开放时间">
          <!-- <el-input
            type="textarea"
            v-model="addEditForm.availableTimes"
            placeholder="请输入开放时间 "
          ></el-input> -->
          <el-checkbox-group v-model="choosingTimes">
            <el-checkbox
              :label="item.value"
              v-for="(item, index) in chooseTimes"
              :key="index"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item v-if="user.role === 1">
          <!-- 超级管理员才显示 -->
          <el-radio-group v-model="addEditForm.role">
            <el-radio :label="3">教学场地</el-radio>
            <el-radio :label="4">运动管场地</el-radio>
            <el-radio :label="5">活动场地</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addEditForm.status">
            <el-option label="开放" value="open" />
            <el-option label="关闭" value="closed" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addEditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 预约对话框 -->
    <el-dialog v-model="reservationDialogVisible" title="预约场馆">
      <el-form
        :model="reservationForm"
        :rules="reservationRules"
        ref="reservationFormRef"
        label-width="100px"
      >
        <el-form-item label="预约日期" prop="reservationDate">
          <el-date-picker
            v-model="reservationForm.reservationDate"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <!-- <el-form-item label="开始时间" prop="startTime">
          <el-time-picker v-model="reservationForm.startTime" format="HH:mm" placeholder="选择时间" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-time-picker v-model="reservationForm.endTime" format="HH:mm" placeholder="选择时间" />
        </el-form-item> -->
        <el-form-item label="时间" prop="times">
          <el-checkbox-group v-model="reservationForm.times">
            <el-checkbox
              :label="item.value"
              v-for="(item, index) in chooseTimes"
              :key="index"
              :disabled="disabledTimes.includes(item.value)"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="活动名称" prop="eventName">
          <el-input
            v-model="reservationForm.eventName"
            placeholder="请输入活动名称"
          />
        </el-form-item>
        <el-form-item label="参与人数" prop="numPeople">
          <el-input-number
            v-model="reservationForm.numPeople"
            :min="1"
            :max="reservationForm.maxNumber"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reservationDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReservation">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { Location } from '@element-plus/icons-vue';
import { chooseTimes, formatTimes } from '../utils/time';
import moment from 'moment';
import { roleType, getTableHeight } from '../utils/role';

const choosingTimes = ref([]);
const venues = ref([]);
const current = ref(1);
const size = ref(10);
const total = ref(0);
// const name =ref('');
// const status = ref('');
const loading = ref(false);
const query = reactive({
  name: '',
  status: '',
});
// 创建一个响应式引用来存储用户信息
const user = ref(null);

// 计算属性来判断是否为管理员
const isAdmin = computed(
  () => user.value && [1, 3, 4, 5].includes(user.value.role)
);

const addEditDialogVisible = ref(false);
const addEditForm = reactive({
  venueId: '',
  name: '',
  address: '',
  capacity: 1,
  availableTimes: '',
  status: 'open',
  role: 3,
});
const editMode = ref(false);
const addEditFormRef = ref(null);

const rules = {
  name: [{ required: true, message: '请输入场馆名称', trigger: 'blur' }],
  address: [{ required: true, message: '请输入场馆地址', trigger: 'blur' }],
  capacity: [{ required: true, message: '请输入容纳人数', trigger: 'blur' }],
  availableTimes: [
    { required: true, message: '请输入开放时间', trigger: 'blur' },
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
};

const load = async () => {
  loading.value = true;
  try {
    const role = user.value.role;
    const response = await axios.get('http://localhost:8080/api/venues/list', {
      params: {
        pageNum: current.value,
        pageSize: size.value,
        role,
        ...query,
      },
    });
    console.log('API响应:', response.data);
    if (response.data.status === 200) {
      venues.value = response.data.data.records;
      total.value = response.data.data.total;
      current.value = response.data.data.current;
      size.value = response.data.data.size;
    } else {
      ElMessage.error(response.data.message || '获取场馆信息失败');
    }
  } catch (error) {
    ElMessage.error('请求场馆信息出错,请登录: ' + error.message);
  } finally {
    loading.value = false;
  }
};

// 此方法废弃
const searchVenueByName = async () => {
  if (query.status != '') {
    //通过状态搜索
    loading.value = true;
    try {
      const response = await axios.get(
        `http://localhost:8080/api/venues/status/${query.status}`
      );
      if (response.data.status === 200) {
        venues.value = response.data.data;
        total.value = venues.value.length;
      } else {
        ElMessage.error(response.data.message || '未找到符合条件的场馆');
        venues.value = [];
        total.value = 0;
      }
    } catch (error) {
      ElMessage.error('查询场馆失败: ' + error.message);
      venues.value = [];
      total.value = 0;
    } finally {
      loading.value = false;
    }
  } else if (query.name != '') {
    //通过名字搜索

    loading.value = true;
    try {
      const response = await axios.get(
        `http://localhost:8080/api/venues/name/${encodeURIComponent(
          query.name
        )}`
      );
      if (response.data.status === 200) {
        venues.value = [response.data.data];
        total.value = 1;
      } else {
        ElMessage.error(response.data.message || '未找到场馆');
        venues.value = [];
        total.value = 0;
      }
    } catch (error) {
      ElMessage.error('搜索场馆失败: ' + error.message);
      venues.value = [];
      total.value = 0;
    } finally {
      loading.value = false;
    }
  } else {
    ElMessage.warning('请输入场馆名称');
    return;
  }
};

const clear = () => {
  Object.keys(query).forEach((key) => (query[key] = ''));
  current.value = 1;
  load();
};

const handleDelete = async (venueId) => {
  try {
    const response = await axios.delete(
      `http://localhost:8080/api/venues/delete/${venueId}`
    );
    if (response.data.status === 200) {
      ElMessage.success('删除成功');
      load();
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    ElMessage.error('删除失败: ' + error.message);
  }
};

const openAddDialog = () => {
  editMode.value = false;
  Object.keys(addEditForm).forEach((key) => (addEditForm[key] = ''));
  const userStr = sessionStorage.getItem('user') || '{}';
  const userObj = JSON.parse(userStr);
  if ([3, 4, 5].includes(userObj.role)) {
    addEditForm.role = userObj.role;
  } else {
    addEditForm.role = 3;
  }
  choosingTimes.value = chooseTimes.map((item) => item.value);
  addEditDialogVisible.value = true;
};

const openEditDialog = async (venue) => {
  editMode.value = true;
  try {
    const response = await axios.get(
      `http://localhost:8080/api/venues/${venue.venueId}`
    );
    if (response.data.status === 200) {
      Object.assign(addEditForm, response.data.data);
      choosingTimes.value = addEditForm.availableTimes.split(',');
      addEditDialogVisible.value = true;
    } else {
      ElMessage.error(response.data.message || '获取场馆详情失败');
    }
  } catch (error) {
    ElMessage.error('获取场馆详情失败: ' + error.message);
  }
};

// -------------------------------------------------------- 添加、编辑球馆信息
const handleEdit = async () => {
  addEditFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        addEditForm.availableTimes = choosingTimes.value.join(',');
        const response = await axios[editMode.value ? 'put' : 'post'](
          `http://localhost:8080/api/venues/${
            editMode.value ? 'update' : 'create'
          }`,
          addEditForm
        );
        if (response.data.status === 200) {
          ElMessage.success('操作成功');
          addEditDialogVisible.value = false;
          load();
        } else {
          ElMessage.error(response.data.message || '操作失败');
        }
      } catch (error) {
        ElMessage.error('操作失败: ' + error.message);
      }
    }
  });
};

const handleReservation = (venue) => {
  const userInfo = JSON.parse(sessionStorage.getItem('user'));
  if (!userInfo || !userInfo.id) {
    ElMessage.error('请先登录');
    return;
  }

  reservationForm.userId = userInfo.id;
  reservationForm.venueId = venue.venueId;
  reservationForm.reservationDate = new Date();
  reservationForm.maxNumber = venue.capacity;
  // reservationForm.startTime = new Date();
  // reservationForm.endTime = new Date();
  reservationForm.times = [];
  reservationForm.eventName = '';
  reservationForm.numPeople = 1;
  reservationForm.status = '待审核';
  reservationDialogVisible.value = true;
};

const submitReservation = () => {
  reservationFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const formattedReservation = {
          ...reservationForm,
          reservationDate: formatDate(reservationForm.reservationDate),
          // startTime: formatTimeWithSeconds(reservationForm.startTime),
          // endTime: formatTimeWithSeconds(reservationForm.endTime),
          times: reservationForm.times.join(','),
          status: reservationForm.status,
        };
        const reservationResponse = await axios.post(
          'http://localhost:8080/api/reservations/create',
          formattedReservation
        );
        console.log('Reservation response:', reservationResponse.data);

        if (reservationResponse.data.status === 200) {
          ElMessage.success('预约成功');
          const date = moment(formattedReservation.reservationDate).format(
            'YYYY-MM-DD'
          );
          const notificationData = {
            title: `预约成功通知 - ${reservationForm.eventName}`,
            content: `成功预约场地：${addEditForm.name}，预约时间：${date},时间${formattedReservation.times}点，活动名称：${reservationForm.eventName}，人数：${reservationForm.numPeople}。`,
            userId: reservationForm.userId,
          };

          // 调用通知接口
          const notificationResponse = await axios.post(
            'http://localhost:8080/api/tongzhi/create',
            notificationData
          );
          console.log('Notification response:', notificationResponse.data);

          if (notificationResponse.data.status === 200) {
            ElMessage.success('通知已发送');
          } else {
            ElMessage.error(
              notificationResponse.data.message || '通知发送失败'
            );
          }

          reservationDialogVisible.value = false;
        } else {
          ElMessage.error(reservationResponse.data.message || '预约失败');
        }
      } catch (error) {
        if (error.response && error.response.status === 400) {
          const errorMessage =
            error.response.data.message || '预约失败，请检查输入信息';
          ElMessage.error('预约失败: ' + errorMessage);
          console.error('预约失败:', error.response.data);
        } else {
          ElMessage.error('预约失败: ' + error.message);
          console.error('预约失败:', error);
        }
      }
    }
  });
};

const handleSizeChange = (newSize) => {
  size.value = newSize;
  current.value = 1;
  load();
};

const handleCurrentChange = (newPage) => {
  current.value = newPage;
  load();
};

const formatDate = (date) => {
  if (!date) return '';
  return moment(date).format('YYYY-MM-DD');
};

const formatTimeWithSeconds = (time) => {
  if (!time) return '';
  const hours = time.getHours().toString().padStart(2, '0');
  const minutes = time.getMinutes().toString().padStart(2, '0');
  const seconds = time.getSeconds().toString().padStart(2, '0');
  return `${hours}:${minutes}:${seconds}`;
};

// const formatAvailableTimes = (availableTimes) => {
//   try {
//     const times = JSON.parse(availableTimes);
//     return Object.entries(times)
//       .map(([days, hours]) => `${days}: ${hours}`)
//       .join(', ');
//   } catch (error) {
//     return availableTimes;
//   }
// };

const reservationDialogVisible = ref(false);
const reservationForm = reactive({
  userId: 0,
  venueId: 0,
  reservationDate: '',
  startTime: new Date(),
  endTime: new Date(),
  eventName: '',
  numPeople: 1,
  status: '待审核',
});

const reservationRules = {
  reservationDate: [
    { required: true, message: '请选择预约日期', trigger: 'change' },
  ],
  // startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  // endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  times: [
    { type: 'array', required: true, message: '请选择时间', trigger: 'change' },
  ],
  eventName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  numPeople: [{ required: true, message: '请输入参与人数', trigger: 'change' }],
};

const reservationFormRef = ref(null);

const disabledTimes = ref([]);
watch(
  () => reservationForm.reservationDate,
  async (date) => {
    const res = await axios.get('http://localhost:8080/api/reservations/list', {
      params: {
        pageNum: 1,
        pageSize: 999,
        venueId: reservationForm.venueId,
        date: moment(date).format('YYYY-MM-DD'),
      },
    });
    const times = [];
    res.data.data.records.map((item) => {
      if (item.times) {
        const arr = item.times.split(',');
        times.push(...arr);
      }
    });
    disabledTimes.value = times;
  }
);

onMounted(() => {
  // 在组件挂载时从 sessionStorage 获取用户信息
  const userDataString = sessionStorage.getItem('user');
  if (userDataString) {
    user.value = JSON.parse(userDataString);
  }
  load();
});
</script>

<style scoped>
.venue-list {
  padding: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: center;
}
</style>
